﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;
using Rose.Models;
using Rose.Helper;

namespace Rose.Movies
{
    public class DownloadAndAddData
    {
        private Database_MovieEntities db = new Database_MovieEntities();

        private string DownloadImage(string imagepath, string savepath)
        {
            try
            {
                if (!Directory.Exists(savepath))
                {
                    Directory.CreateDirectory(savepath);
                }
                

                string[] extensions = imagepath.Split('/');
                string extension = extensions[extensions.Length - 1];

                if (File.Exists(savepath + extension))
                {
                    return savepath + extension;
                }

                HttpWebResponse response = null;
                Stream instream = null;
                Stream outstream = null;

                outstream = File.OpenWrite(savepath + extension);

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(imagepath);
                response = (HttpWebResponse)request.GetResponse();

                instream = response.GetResponseStream();


                byte[] buffer = new byte[1024 * 4];
                int read = 0;
                while ((read = instream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    outstream.Write(buffer, 0, read);
                }

                if (instream != null)
                    instream.Close();
                if (outstream != null)
                    outstream.Close();
                if (response != null)
                    response.Close();

                return savepath + extension;
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return string.Empty;
            }



        }


        public List<string> DownloadImageList(List<string> imageList, string savepath)
        {
            List<string> returnString = new List<string>();
            foreach (string item in imageList)
            {
                try
                {
                    string addString=DownloadImage(item, savepath);
                    
                        returnString.Add(addString);
                }
                catch
                {
                    continue;
                }

            }
            return returnString;
        }

        public void AddMovyToDatabase(string item, int camera)
        {

            try
            {
                DateTime datetime = DateTime.Today;

                var datamovy = db.Movies.Where(c => c.CameraId == camera && c.Time == datetime && c.Content == item).FirstOrDefault();

                if (datamovy != null)
                    return;

                Movy model = new Movy()
                {
                    Content = item,
                    MovieId = Guid.NewGuid(),
                    Time = datetime,
                    CameraId = camera
                };

                db.AddToMovies(model);
                db.SaveChanges();

            }
            catch
            {
                return;
            }

        }

        #region 添加数据


        //public void AddMovyToDatabase(List<string> returnModel, int camera)
        //{
        //    //the returnModel is the page from the movie introduction;
        //    int count = 0;
        //    try
        //    {
        //        DateTime datetime = DateTime.Today;

        //        if (returnModel.Count <= 0)
        //            return;

        //        var datalist = db.Movies.Where(c => c.CameraId == camera && c.Time == datetime);

        //        if (datalist.Count() > 0)
        //            return;
        //        //数据库中存在信息就不进行下载更新了

        //        foreach (string item in returnModel)
        //        {
        //            count++;
        //            Movy model = new Movy()
        //            {
        //                Content = item,
        //                MovieId = Guid.NewGuid(),
        //                Time = datetime,
        //                CameraId = camera
        //            };


        //            //检测数据库中不存在原来的数据
                    

        //            db.AddToMovies(model);
        //            if (count % 5 == 0)
        //            {
        //                db.SaveChanges();
        //                count = 0;
        //            }

        //        }
        //        db.SaveChanges();

        //    }
        //    catch
        //    { return; }
        //}

        

        //public string BeforeMovyToDatabase(string item,string newimagepath,string savepath)
        //{ 
        //     List<string> imagelist=
        //}
      
           
    

        //public void AddCameraToDatabase(string title, int id)
        //{
        //    try
        //    {
        //        Camera model = new Camera()
        //        {
        //            CameraName = title,
        //            CameraId = id,
        //            CityId = 561
        //        };

        //        db.AddToCameras(model);
        //        db.SaveChanges();
        //    }
        //    catch
        //    {
        //        throw;
        //    }


        //}

        


        //public void DealWithACamera(string url, int cameraId,string savepath)
        //{

        //    WormShareContentHelpModel share = new WormShareContentHelpModel();

        //    string source = share.GetUft8Html(url);

        //    HtmlTag htmlhelp = new HtmlTag();


        //    string movietag = htmlhelp.GetUniqTag(source, "div", "id=\"theaterShowtimeListDiv\"");
        //    //针对当前的网站，数据是这个样子的

        //    List<string> returnModel = htmlhelp.GetTagCollect(movietag, "div", "class=\"table mt25\"");


        //    DateTime today = DateTime.Today;

        //    string daypath = today.Year + "\\" + today.Month + "\\" + today.Day + "\\";

        //    foreach (string item in returnModel)
        //    {
        //        List<string> imagelist =htmlhelp.GetImageSrc(item);
        //       string imagepath = DownloadImageList(imagelist,savepath + daypath + cameraId + @"\");

        //        if (!string.IsNullOrEmpty(imagepath))
        //        {

        //            List<string> prehttpsrc = htmlhelp.GetImageSrc(item);
        //            if (prehttpsrc.Count > 0)
        //            {
        //                 string newitem= item.Replace(prehttpsrc[0], imagepath);
        //                AddMovyToDatabase(newitem, cameraId);
        //                Console.WriteLine("down ok");
        //            }
                  
        //        }


        //    }


        //}

        //public void DealWithCameras(string url)
        //{


        //    WormShareContentHelpModel share = new WormShareContentHelpModel();
        //    string source = share.GetUft8Html(url);

        //    HtmlTag help = new HtmlTag();


        //    string movietag = help.GetUniqTag(source, "div", "id=\"cinemaListDiv\"");

        //    List<string> returnModel = help.GetTagCollect(movietag, "div", "class=\"clearfix mt20\"");

        //}
        #endregion
    }
}